import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {

    Connection conn;

    public synchronized List<String> queryAllStudentCode() {
        ArrayList<String> res = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            res = new ArrayList<>();
            conn = H2Utils.getConnection();
            st = conn.createStatement();
            rs = st.executeQuery("SELECT student_code FROM student");
            while (rs.next()) {
                String studentCode = rs.getString("student_code");
                res.add(studentCode);
            }
        } catch (Exception e) {
            return null;
        } finally {
            H2Utils.close(conn, st, rs);
        }
        return res;
    }

    public synchronized void InsertStudentCode(String studentCode) {
        if (StringUtils.isBlank(studentCode))
            return;
        PreparedStatement st = null;
        try {
            conn = H2Utils.getConnection();
            st = conn.prepareStatement("INSERT INTO student(student_code) VALUES (?)");
            st.setString(1, studentCode);
            st.execute();
        } catch (Exception e) {
        } finally {
            H2Utils.close(conn, st, null);
        }
    }

    public synchronized void InsertStudentCodeList(List<String> studentCodeList) {
        PreparedStatement st = null;
        try {
            conn = H2Utils.getConnection();
            st = conn.prepareStatement("INSERT INTO student(student_code) VALUES (?)");
            for (String s : studentCodeList) {
                st.setString(1, s);
                st.execute();
            }
        } catch (Exception e) {
        } finally {
            H2Utils.close(conn, st, null);
        }
    }

    public synchronized void deleteStudentCode(String studentCode) {
        PreparedStatement st = null;
        try {
            conn = H2Utils.getConnection();
            st = conn.prepareStatement("DELETE FROM student WHERE student_code=?");
            st.setString(1, studentCode);
            st.execute();
        } catch (Exception e) {
        } finally {
            H2Utils.close(conn, st, null);
        }
    }

}
